package com.emily.test.controller;

import ch.qos.logback.core.pattern.color.YellowCompositeConverter;
import com.alibaba.fastjson.JSONObject;
import com.emily.test.constant.ReturnValueConstants;
import com.emily.test.controller.result.ResponseResult;
import com.emily.test.model.*;
import com.emily.test.service.RedisService;
import com.emily.test.service.TCompanyResourceService;
import com.emily.test.service.TCompanyService;
import com.emily.test.service.TResourceService;
import com.emily.test.utils.ConstentUtil;
import com.emily.test.utils.HeaderUtil;
import com.emily.test.vo.CompanyVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping(value = "tCompanyResourceController")
@Api(value = "TCompanyResourceApi", description = "TCompanyResource接口类", position = 1, produces = MediaType.APPLICATION_JSON_VALUE)
public class TCompanyResourceController {
    private Logger logger = LoggerFactory.getLogger(TMenuController.class);
    @Autowired
    private TCompanyResourceService tCompanyResourceService;

    @Autowired
    private TCompanyService tCompanyService;

    @Autowired
    private TResourceService tResourceService;

    @Autowired
    private RedisService redisService;

    /**
     * 插入公司与资源关联表信息
     * @param jsonObject 包含公司（companyId）与资源（resourceIds）关联表集合 ，其中companyId格式为Integer，resourceIds格式为List集合
     * @return
     */
    @ApiOperation(value="插入角色与资源的对应关系", notes="tRoleResource")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "公司ID", required = true),
            @ApiImplicitParam(name = "resourceIds", value = "资源ID", required = true)
    })
    @PostMapping(value = "insertTCompanyResourceInfo")
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public ResponseResult insertTCompanyResourceInfo(@RequestBody JSONObject jsonObject){
        Map<String,Object> map=jsonObject.getInnerMap();
        try {
            int num=tCompanyResourceService.insertTCompanyResourceInfo(map);
            if(num==0){
                logger.error("未插入任何公司与资源关联表的数据,数据集合={}",map);
                return ResponseResult.fail(ReturnValueConstants.ADD_FAILURE);
            }
            logger.info("插入t_company_resource成功，集合map={}",map);
            return ResponseResult.success(ReturnValueConstants.ADD_SUCCESS,num);
        } catch (Exception e) {
            logger.error("插入t_company_resource异常:{}",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.ADD_FAILURE);
        }
    }


    /**
     *根据公司ID删除对应的资源ID
     * @param companyId 角色ID
     * @return
     */
    @ApiOperation(value="根据公司ID删除对应的资源ID", notes="根据公司ID删除对应的资源ID")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "公司ID", required = true)
    })
    @PostMapping(value = "deleteTCompanyResourceByComId/{companyId}")
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public ResponseResult deleteTCompanyResourceByComId(@PathVariable("companyId") Integer companyId){
        if(ConstentUtil.isEmpty(companyId)){
            return ResponseResult.fail("公司"+ReturnValueConstants.IS_NOT_ALLOW_NULL);
        }
        try {
            int num= tCompanyResourceService.deleteTCompanyResourceByComId(companyId);
            logger.info("删除t_company_resource成功，删除数量={}",num);
            return ResponseResult.success(ReturnValueConstants.DELATE_SUCCESS,num);
        } catch (Exception e) {
            logger.error("删除t_company_resource异常:{}",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.DELATE_FAILURE);
        }
    }

    /**
     * 查询公司对应的资源信息列表
     * @return
     */
    @ApiOperation(value="查询公司对应的资源信息列表", notes="查询公司对应的资源信息列表")
    @ApiImplicitParams({
            // @ApiImplicitParam(name = "companyId", value = "公司ID", required = true)
    })
    @PostMapping(value = "selectResourceListInCompany")
    public ResponseResult selectResourceListInCompany(HttpServletRequest request){
        Integer companyId = HeaderUtil.getCompanyId(request,redisService);
        if(ConstentUtil.isEmpty(companyId)){
            logger.info("查询t_company_resource失败,roleId={}",companyId);
            return ResponseResult.fail("公司"+ReturnValueConstants.IS_NOT_ALLOW_NULL);
        }
        try {
            List<Map<String,Object>> resourceList= tCompanyResourceService.getResourceInfoByCompanyIdList(companyId);
            logger.info("查询t_company_resource成功，list={}",resourceList);
            return ResponseResult.success(ReturnValueConstants.QUERY_SUCCESS,resourceList);
        } catch (Exception e) {
            logger.error("查询t_company_resource异常:{}",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.QUERY_FAILURE);
        }
    }

    /**
     * 根据公司ID查询对应的资源信息列表
     * @param companyId 公司ID
     * @return
     */
    @ApiOperation(value="根据公司ID查询所有相关资源ID", notes="根据公司ID查询所有相关资源ID")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "公司ID", required = true)
    })
    @PostMapping(value = "selectTCompanyReSourceIDByComId/{companyId}")
    public ResponseResult selectTCompanyReSourceIDByComId(@PathVariable("companyId") Integer companyId){
        if(ConstentUtil.isEmpty(companyId)){
            logger.info("查询t_company_resource失败,roleId={}",companyId);
            return ResponseResult.fail("公司"+ReturnValueConstants.IS_NOT_ALLOW_NULL);
        }
        try {
            List<TCompanyResource> tCompanyResourceList= tCompanyResourceService.selectTCompanyReSourceIDByComId(companyId);
            logger.info("查询t_company_resource成功，list={}",tCompanyResourceList);
            return ResponseResult.success(ReturnValueConstants.QUERY_SUCCESS,tCompanyResourceList);
        } catch (Exception e) {
            logger.error("查询t_company_resource异常:{}",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.QUERY_FAILURE);
        }
    }

    /**
     * 更新公司与资源关系信息表
     * @param jsonObject 包含角色（companyId）与资源（resourceIds）关联表集合 ，其中companyId格式为Integer，resourceIds格式为List集合
     * @return
     */
    @ApiOperation(value="修改公司ID对应的资源ID信息", notes="修改公司ID对应的资源ID信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "公司ID", required = true),
            @ApiImplicitParam(name = "resourceIds", value = "资源ID")
    })
    @PostMapping(value = "updateTCompanySourceIdInfo")
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public ResponseResult updateTCompanySourceIdInfo(@RequestBody JSONObject jsonObject){
        System.out.println(jsonObject);
        Map<String,Object> map=jsonObject.getInnerMap();
        Integer companyId=null;
        if(!ConstentUtil.isEmpty(map)){

            companyId= Integer.parseInt(map.get("companyId").toString());
        }
        if(ConstentUtil.isEmpty(companyId)){
            logger.info("修改t_company_resource失败,roleId={}",companyId);
            return ResponseResult.fail("角色"+ReturnValueConstants.IS_NOT_ALLOW_NULL);
        }
        try {
            //删除原有公司与资源的对应关系
            int delNum=tCompanyResourceService.deleteTCompanyResourceByComId(companyId);
            logger.info("删除t_company_resource成功，total={}",delNum);

            //增加新的公司与资源的绑定关系，如果资源信息集合为空，则不需插入
            if(ConstentUtil.isEmpty(map.get("resourceIds"))){
                logger.info("增加t_company_resource成功，map={}",map);
                return ResponseResult.success(ReturnValueConstants.ADD_SUCCESS,0);
            }
            int addNum=tCompanyResourceService.insertTCompanyResourceInfo(map);

            logger.info("修改t_company_resource成功，新增条数:{}",addNum);
            return ResponseResult.success(ReturnValueConstants.UPDATE_SUCCESS,addNum);
        } catch (Exception e) {
            logger.error("更新t_company_resource表异常:{}",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.UPDATE_FAILURE);
        }
    }

    /**
     * 根据公司ID获取角色信息以及所有的资源信息集合，其中公司已经有的资源信息添加selected=1属性，没有的则为selected=0.
     * @param jsonObject
     * @return
     */
    @ApiOperation(value="根据公司ID获取角色信息以及所有的资源信息集合，其中公司已经有的资源信息添加selected=1属性，" +
            "没有的则为selected=0.", notes="TCompanyResource")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "公司ID", required = true)
    })
    @PostMapping(value = "getCompanyAndAllResourceInfoByCompanyId")
    public ResponseResult getCompanyAndAllResourceInfoByCompanyId(@RequestBody JSONObject jsonObject){
        try {
            //角色ID
            Integer companyId=jsonObject.getInteger("id");

            //根据公司ID获取公司信息
            CompanyVO tCompany =tCompanyService.selectCompanyInfoById(companyId);

            //获取公司已经存在的资源信息列表
            List list=new ArrayList();
            list.add(companyId);
            List<Map<String,Object>> tResourceLists= tCompanyResourceService.selectTCompanyResourceInfoByCompanyId(companyId);

            //获取所有启用的资源信息
            TResource tResource=new TResource();
            tResource.setState(1);
            List<TResource> tResourceList=tResourceService.selectResourceListByCondition(tResource);

            Map<String,Object> returnMapList=new HashMap<String,Object>();
            //将公司信息放入map
            returnMapList.put("id",tCompany.getId());
            returnMapList.put("cName",tCompany.getCName());
            returnMapList.put("companyCode",tCompany.getCompanyCode());
            returnMapList.put("companyState", tCompany.getState());
            returnMapList.put("companyDescription",tCompany.getDescription());
            returnMapList.put("companyUpdateTime",tCompany.getUpdateTime());

            //将资源信息放入集合
            List<Map<String,Object>> inputList=new ArrayList<Map<String,Object>>();
            if(!ConstentUtil.isEmpty(tResourceList)){
                for(TResource tResource1 : tResourceList){

                    int allResourceId=tResource1.getId();

                    Map<String,Object> resourceMap=new HashMap<>();
                    resourceMap.put("resourceId",tResource1.getId());
                    resourceMap.put("resName",tResource1.getResName());
                    resourceMap.put("resourceDescription",tResource1.getDescription());
                    resourceMap.put("pageurl",tResource1.getPageurl());
                    resourceMap.put("img",tResource1.getImg());
                    resourceMap.put("resourceState",tResource1.getState());
                    resourceMap.put("pid",tResource1.getPid());
                    resourceMap.put("resourceUpdateTime",tResource1.getUpdateTime());

                    if(!ConstentUtil.isEmpty(tResourceLists)){
                        for(Map<String,Object> rMap : tResourceLists){
                            int partResourceId=(int) rMap.get("resourceId");
                            //添加公司含有的角色信息到map，并且为其添加属性selected ： true
                            if(allResourceId==partResourceId){
                                resourceMap.put("selected","1");
                                break;
                            }else{
                                resourceMap.put("selected","0");
                            }
                        }
                    }else{
                        resourceMap.put("selected","0");
                    }
                    inputList.add(resourceMap);
                }
            }
            returnMapList.put("resourceList",inputList);
            logger.info("查询公司资源信息成功:{}",returnMapList);
            return ResponseResult.success(returnMapList);
        } catch (Exception e) {
            logger.error("查询公司资源信息异常",e);
            e.printStackTrace();
            return ResponseResult.fail("查询失败");
        }

    }


    /**
     * 根据公司信息查询公司与资源的关联信息列表
     * @param jsonObject 包含公司信息查询条件
     * @return
     */
    @ApiOperation(value="根据公司信息查询公司与资源的关联信息列表", notes="根据公司信息查询公司与资源的关联信息列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "公司ID"),
            @ApiImplicitParam(name = "cName", value = "公司名称"),
            @ApiImplicitParam(name = "companyCode", value = "公司CODE"),
            @ApiImplicitParam(name = "state", value = "公司状态"),
            @ApiImplicitParam(name = "description", value = "备注"),
            @ApiImplicitParam(name = "updateTime", value = "更新时间")
    })
    @PostMapping("getCompanyResourceInfoListByCompanyCondition")
    public ResponseResult getCompanyResourceInfoListByCompanyCondition(@RequestBody(required = false) JSONObject jsonObject) throws Exception {

        List<Map<String,Object>> all_list = new ArrayList<Map<String,Object>>();
        List<TCompany> haveResourceCompanyMap = new ArrayList<TCompany>();
        TCompany companyVO= (TCompany) ConstentUtil.json2Object(jsonObject,TCompany.class);
        try {
            //根据条件查询公司信息列表
            List<TCompany> companyList=tCompanyService.getCompanyList(companyVO);
            if(!ConstentUtil.isEmpty(companyList)){
                String stringBuffer="";
                for(TCompany tCompany1 : companyList){
                    stringBuffer +=tCompany1.getId()+",";
                }
                stringBuffer= stringBuffer.substring(0,stringBuffer.length()-1).trim();
                List li=ConstentUtil.strToList(stringBuffer);

                List<Map<String,Object>> tResourceList= tCompanyResourceService.selectTCompanyResourceInfoByCompanyIds(li);
                if(!ConstentUtil.isEmpty(tResourceList)){
                    for(TCompany tc : companyList){
                        Integer comId=tc.getId();
                        for(Map mp :tResourceList){
                            Integer companyId= (Integer) mp.get("companyId");
                            if(comId.equals(companyId)){
                                haveResourceCompanyMap.add(tc);
                                break;
                            }
                        }
                    }

                    for(TCompany tcs : haveResourceCompanyMap){
                        Map<String,Object> comMap=ConstentUtil.beanToMap(tcs);
                        List ls=new ArrayList();
                        Integer comIds=tcs.getId();
                        for(Map mp :tResourceList){
                            Integer companyIds= (Integer) mp.get("companyId");
                            if(comIds.equals(companyIds)){
                                ls.add(mp);
                            }
                        }
                        comMap.put("data",ls);
                        all_list.add(comMap);
                    }

//                        for (int i = 0; i < tResourceList.size(); i++) {
//                            Integer comId= (Integer) tResourceList.get(i).get("companyId");
//                            for (int j = 0; j < companyList.size(); j++) {
//                                Integer companyId=companyList.get(j).getId();
//                                if(companyId.equals(comId)) {
//                                    hm.put("companyId",companyId);
//                                    hm.put("cName", companyList.get(j).getcName());
//                                    list1.add(tResourceList.get(i));
//                                    hm.put("data",list1);
//                                    all_list.add(hm);
//                                    break;
//                                }
//                            }
//                        }
                }
            }
            logger.info("查询公司与资源信息成功:{}",all_list);
            return ResponseResult.success(all_list);
        } catch (Exception e) {
            logger.error("查询公司与资源信息异常:",e);
            e.printStackTrace();
            return ResponseResult.fail("查询失败");
        }
    }

    /**
     * 查询没有资源的公司信息
     *
     * @return
     */
    @ApiOperation(value="查询没有资源的公司信息", notes="查询没有资源的公司信息")
    @ApiImplicitParams({
//            @ApiImplicitParam(name = "companyId", value = "公司ID", required = true)
    })
    @PostMapping(value = "selectTCompanyWithOutResource")
    public ResponseResult selectTCompanyWithOutResource(){
        try {
            List<TCompany> tCompanyList= tCompanyService.selectTCompanyWithOutResource();
            logger.info("查询t_company成功，list={}",tCompanyList);
            return ResponseResult.success(ReturnValueConstants.QUERY_SUCCESS,tCompanyList);
        } catch (Exception e) {
            logger.error("查询t_company异常:{}",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.QUERY_FAILURE);
        }
    }
}

